﻿using Infrastructure.Model;
using Microsoft.AspNetCore.Http;
using ShareCode.KeyValue;
using System;
using System.Collections.Generic;
using System.Configuration.Internal;
using System.Formats.Tar;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure.Util.Helper
{
    public static class UploadFileHelper
    {

        /// <summary>
        /// 取的默认文件，或者说是默认图片
        /// </summary>
        /// <param name="fileUsage"></param>
        /// <returns></returns>
        public static string GetDefaultFileUsagePath(EnumFileUsage fileUsage)
        {
            //默认的子级
            var tempPath = fileUsage switch
            {
                EnumFileUsage.Default => "Default.jpg",
                EnumFileUsage.UserAvatar => "UserAvatar.jpg",
                EnumFileUsage.OrgIcon => "OrgIco.jpg",
                EnumFileUsage.CorpusVersionCover => "CorpusVersionCover.jpg",
                _ => ""
            };

            if (string.IsNullOrEmpty(tempPath))
            {
                return tempPath;
            }

            var baseDic = ConfigurationManagerModel.ThreadSafeReadString("FileSaveFolder:BaseFolder");

            if (baseDic == default)
            {
                baseDic = "";
            }

            return Path.Combine(baseDic, tempPath).Trim('\\', '/');
        }

        private static string GetFilePath(IFormFile formFile, EnumFileUsage fileUsage)
        {
            var dateDic = DateTime.Now.ToString("yyyyMMdd");

            var baseDic = ConfigurationManagerModel.ThreadSafeReadString("FileSaveFolder:BaseFolder").Trim('\\','/');

            if (baseDic == default)
            {
                baseDic = "";
            }

            var sonPathName = fileUsage.ToString();
            var sonPath = ConfigurationManagerModel.ThreadSafeReadString($"FileSaveFolder:{sonPathName}");

            if (sonPath.StartsWith("/"))
            {
                return sonPath;
            }

            baseDic = Path.Combine(baseDic, sonPath, dateDic);

            var srtFolder = Path.Combine(AppContext.BaseDirectory, baseDic);
            if (!Directory.Exists(srtFolder))
            {
                Directory.CreateDirectory(srtFolder);
            }

            var FileName = Path.GetRandomFileName();
            FileName = Path.ChangeExtension(FileName, Path.GetExtension(formFile.FileName));

            baseDic = Path.Combine(baseDic, FileName);

            return baseDic.Trim('\\', '/');
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="formFile"></param>
        /// <param name="fileUsage"></param>
        /// <returns>文件路径</returns>
        public static string SaveFormFile(IFormFile formFile, EnumFileUsage fileUsage)
        {
            if (formFile == default)
            {
                return GetDefaultFileUsagePath(fileUsage);
            }

            var baseDic = GetFilePath(formFile, fileUsage);
            var FullPath = Path.Combine(AppContext.BaseDirectory, baseDic);

            using var fs = new FileStream(FullPath, FileMode.Create);

            formFile.CopyTo(fs);
            fs.Flush();

            return baseDic;

        }

        /// <summary>
        /// 从列表中选择一个文件类型来保存
        /// </summary>
        /// <param name="formFile"></param>
        /// <param name="fileUsage"></param>
        /// <returns></returns>
        public static string SaveFormFile(List<IFormFile> formFile, EnumFileUsage fileUsage)
        {
            if (formFile == null || formFile.Count < 1) {
                return GetDefaultFileUsagePath(fileUsage);
            }

            var fileName = fileUsage.ToString() + ".";

            var theFile = formFile.FirstOrDefault(f => f.FileName.StartsWith(fileName));
            if (theFile == null)
            {
                return GetDefaultFileUsagePath(fileUsage);
            }

            return SaveFormFile(theFile, fileUsage);
        }
        public static string SaveFormFile(List<IFormFile> formFile, EnumFileUsage fileUsage, EnumFileUsage asFileUsage) {
            if (formFile == null || formFile.Count < 1)
            {
                return GetDefaultFileUsagePath(asFileUsage);
            }

            var fileName = fileUsage.ToString() + ".";

            var theFile = formFile.FirstOrDefault(f => f.FileName.StartsWith(fileName));
            if (theFile == null)
            {
                return GetDefaultFileUsagePath(asFileUsage);
            }

            return SaveFormFile(theFile, asFileUsage);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="formFile"></param>
        /// <param name="fileUsage"></param>
        /// <returns></returns>
        public static List<string> SaveFormFiles(List<IFormFile> formFile, EnumFileUsage fileUsage)
        {
            var fileName = fileUsage.ToString();

            var theFiles = formFile.Where(f => f.FileName.StartsWith(fileName)).ToList();
            if (theFiles == null || theFiles.Count < 1)
            {
                return [];
            }

            List<string> re = [];

            foreach (var item in theFiles)
            {
                re.Add(SaveFormFile(item, fileUsage));
            }

            return re;
        }
    }
}
